package com.mbc.web.common.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.mbc.common.entities.Country;
import com.mbc.web.common.client.ButtonActionType;
import com.mbc.web.common.client.ClientSingleton;
import com.mbc.web.common.client.CommonControllerMgr;
import com.mbc.web.common.client.CommonMessage;
import com.mbc.web.common.client.ViewUtils;
import com.mbc.web.common.client.ui.control.MButton;
import com.mbc.web.common.client.ui.control.MTextBox;
import com.mbc.web.common.shared.HttpStatus;

public class FrmCountry extends Composite {

	@UiField
	MButton btnSave;
	@UiField
	MButton btnEdit;
	@UiField
	MButton btnDelete;
	@UiField
	MButton btnReset;
	@UiField
	MButton btnNew;
	@UiField
	MButton btnList;
	@UiField
	MButton btnBack;

	@UiField
	MTextBox txtCountryCode;
	@UiField
	MTextBox txtName;

	private long countryId;
	private Country country;
	byte action_type;

	private static FrmCountryUiBinder uiBinder = GWT
			.create(FrmCountryUiBinder.class);

	interface FrmCountryUiBinder extends UiBinder<Widget, FrmCountry> {
	}

	public FrmCountry() {
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		onBtnNewClick(null);
	}

	public FrmCountry(Country country) {
		initWidget(uiBinder.createAndBindUi(this));
		initialize();
		this.country = country;
		bindControls(country);
		enableControls(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnDelete.setEnabled(true);
		btnReset.setEnabled(false);
	}

	private void initialize() {
		
		txtCountryCode.getElement().setAttribute("style", "text-transform: uppercase;");
		
		Scheduler.get().scheduleDeferred(new ScheduledCommand() {

			@Override
			public void execute() {
				txtCountryCode.setFocus(true);
			}
		});

		txtName.addKeyDownHandler(new KeyDownHandler() {

			@Override
			public void onKeyDown(KeyDownEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					event.preventDefault();
					TextBox l_txt = (TextBox) event.getSource();
					if (l_txt == txtName)
						btnSave.setFocus(true);
				}

			}
		});
	}

	private void enableControls(boolean enabled) {
		txtCountryCode.setEnabled(enabled);
		txtName.setEnabled(enabled);
	}

	private void bindControls(Country country) {
		txtCountryCode.setText(country.getCountryCode());
		txtName.setText(country.getName());
		countryId = country.getCountryId();
	}

	private native void jsClear()/*-{
		$wnd.$("input").val("");
	}-*/;

	private void clear() {
		jsClear();
		countryId = 0;
		country = null;
	}

	private Country bindCountry() {
		country = new Country();
		country.setCountryId(countryId);
		country.setCountryCode(txtCountryCode.getText());
		country.setName(txtName.getText());
		return country;
	}

	private AsyncCallback<Integer> actionCallback() {
		return new AsyncCallback<Integer>() {

			@Override
			public void onSuccess(Integer result) {
				ViewUtils.stopAjaxLoader();
				if (result == HttpStatus.OK) {
					switch (action_type) {
					case ButtonActionType.action_save:
						ViewUtils
								.showSuccessMessage(CommonMessage.saved_message);
						ClientSingleton.changeView(new SearchCountry(txtCountryCode.getText(), SearchCountry.SAVE));
						break;
					case ButtonActionType.action_delete:
						ViewUtils
								.showSuccessMessage(CommonMessage.deleted_message);
						ClientSingleton.changeView(new SearchCountry(txtCountryCode.getText(), SearchCountry.DELETE));
						break;
					}
					
				} else {
					if (result == HttpStatus.INTERNAL_SERVER_ERROR)
						ViewUtils
								.showErrorMessage(CommonMessage.internal_server_error_message);
					else if (result == HttpStatus.BAD_REQUEST)
						ViewUtils.showErrorMessage(CommonMessage
								.getAlreadyExistedMessage("Country Code("
										+ txtCountryCode.getText() + ")"));
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub

			}
		};
	}

	@UiHandler("btnNew")
	void onBtnNewClick(ClickEvent event) {
		clear();
		enableControls(true);
		txtCountryCode.setFocus(true);
		btnSave.setEnabled(true);
		btnEdit.setEnabled(false);
		btnDelete.setEnabled(false);
		btnReset.setEnabled(false);
	}

	@UiHandler("btnSave")
	void onBtnSaveClick(ClickEvent event) {
		if (ViewUtils.isValidate()) {
			action_type = ButtonActionType.action_save;
			ViewUtils.startAjaxLoader(CommonMessage.saving_message);
			if (countryId == 0)
				CommonControllerMgr.createCountry(bindCountry(),
						actionCallback());
			else
				CommonControllerMgr.updateCountry(bindCountry(),
						actionCallback());

		}
	}

	@UiHandler("btnEdit")
	void onBtnEditClick(ClickEvent event) {
		if (countryId != 0) {
			btnReset.setEnabled(true);
			btnSave.setEnabled(true);
			btnEdit.setEnabled(false);
			btnNew.setEnabled(false);
			enableControls(true);
			txtName.setFocus(true);
			txtCountryCode.setEnabled(false);
		}
	}

	@UiHandler("btnDelete")
	void onBtnDeleteClick(ClickEvent event) {
		if (countryId != 0) {
			ViewUtils.showConfirm(CommonMessage.delete_confirm_message,
					new CloseHandler<PopupPanel>() {

						@Override
						public void onClose(CloseEvent<PopupPanel> event) {
							if (ViewUtils.isAlertYes()) {
								action_type = ButtonActionType.action_delete;
								ViewUtils
										.startAjaxLoader(CommonMessage.deleting_message);

								CommonControllerMgr.deleteCountry(
										countryId, actionCallback());

							}
						}
					});
		}
	}

	@UiHandler("btnReset")
	void onBtnResetClick(ClickEvent event) {
		bindControls(country);
		enableControls(false);
		btnReset.setEnabled(false);
		btnSave.setEnabled(false);
		btnEdit.setEnabled(true);
		btnNew.setEnabled(true);
	}

	@UiHandler("btnBack")
	void onBtnBackClick(ClickEvent event) {
		ClientSingleton.changeView(new SearchCountry());
	}
	
	@UiHandler("btnList")
	void onBtnListClick(ClickEvent event) {
		ClientSingleton.changeView(new FrmCountryRpt());
	}
	
	@UiHandler("txtCountryCode")
	void onTxtCountryChange(ChangeEvent event) {
		if (!txtCountryCode.getText().equals("")) {
			Country l_info = new Country();
			l_info.setCountryCode(txtCountryCode.getText());
			ViewUtils.startAjaxLoader(CommonMessage.loading_message);
			CommonControllerMgr
					.findCountryByCode(l_info , getCountryCallback());
		}

	}

	private AsyncCallback<Country> getCountryCallback() {
		return new AsyncCallback<Country>() {

			@Override
			public void onSuccess(Country result) {
				ViewUtils.stopAjaxLoader();
				if (result != null) {
					country = result;
					bindControls(result);
					enableControls(false);
					btnSave.setEnabled(false);
					btnEdit.setEnabled(true);
					btnDelete.setEnabled(true);
					btnEdit.setFocus(true);
				}
			}

			@Override
			public void onFailure(Throwable caught) {

			}
		};
	}
}
